package day05.concurrent02;

import java.util.concurrent.Semaphore;

/**
 * Semaphore 信号量
 */
public class Demo03 {
    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(3);

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    semaphore.acquire();
                    System.out.println(Thread.currentThread()+"获取到信号量");
                    Thread.sleep(3000);
                    System.out.println(Thread.currentThread()+"释放了信号量");
                    semaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    semaphore.acquire();
                    System.out.println(Thread.currentThread()+"获取到信号量");
                    Thread.sleep(4000);
                    System.out.println(Thread.currentThread()+"释放了信号量");
                    semaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    semaphore.acquire();
                    System.out.println(Thread.currentThread()+"获取到信号量");
                    Thread.sleep(5000);
                    System.out.println(Thread.currentThread()+"释放了信号量");
                    semaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    semaphore.acquire();
                    System.out.println(Thread.currentThread()+"获取到信号量");
                    Thread.sleep(2000);
                    System.out.println(Thread.currentThread()+"释放了信号量");
                    semaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    semaphore.acquire();
                    System.out.println(Thread.currentThread()+"获取到信号量");
                    Thread.sleep(6000);
                    System.out.println(Thread.currentThread()+"释放了信号量");
                    semaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
